package com.help10000.rms.ui.activitys

import android.app.Activity
import android.os.Bundle
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.amir.common.beans.RepairInfo
import com.amir.common.beans.ReportData
import com.amir.common.utils.DisplayUtil
import com.amir.common.utils.MoneyEdiTextUtil
import com.amir.common.weight.DuplicateClickProxy
import com.help10000.rms.R
import com.help10000.rms.common.GridSpacingItemDecoration
import com.help10000.rms.common.WeChatPresenter
import com.help10000.rms.mvp.presenter.ReportPresenter
import com.help10000.rms.mvp.view.ReportView
import com.help10000.rms.ui.adapter.OrderReportPhotoItemAdapter
import com.help10000.rms.ui.base.BaseActivity
import com.help10000.rms.weights.EdiTextChangeListener
import com.ypx.imagepicker.ImagePicker
import com.ypx.imagepicker.bean.ImageItem
import com.ypx.imagepicker.bean.MimeType
import com.ypx.imagepicker.data.OnImagePickCompleteListener
import kotlinx.android.synthetic.main.activity_report.*
import kotlinx.android.synthetic.main.layout_report_bottom.*

/**
 * 完工上报
 */
class ReportOrderActivity : BaseActivity<ReportPresenter, ReportView>(), ReportView,
    View.OnClickListener {

    val list = mutableListOf<String>()


    var mAdapter: OrderReportPhotoItemAdapter? = null
    var repairInfo: RepairInfo? = null
    var data: ReportData? = null
    var Revenue01Value = ""
    var Revenue02Value = ""
    var Revenue03Value = ""
    var Revenue04Value = ""
    var Revenue05Value = ""

    var Expense01Value = ""
    var Expense02Value = ""
    var Expense03Value = ""
    var Expense04Value = ""
    var Expense05Value = ""


    override fun getlayoutId(): Int {
        return R.layout.activity_report
    }

    override fun initView() {
        MoneyEdiTextUtil.afterDotTwo(Revenue01)
        MoneyEdiTextUtil.afterDotTwo(Revenue02)
        MoneyEdiTextUtil.afterDotTwo(Revenue03)
        MoneyEdiTextUtil.afterDotTwo(Revenue04)
        MoneyEdiTextUtil.afterDotTwo(Revenue05)

        MoneyEdiTextUtil.afterDotTwo(Expense01)
        MoneyEdiTextUtil.afterDotTwo(Expense02)
        MoneyEdiTextUtil.afterDotTwo(Expense03)
        MoneyEdiTextUtil.afterDotTwo(Expense04)
        MoneyEdiTextUtil.afterDotTwo(Expense05)


    }

    override fun initData(savedInstanceState: Bundle?) {
        repairInfo = intent.getSerializableExtra("data") as RepairInfo
        mPresenter.repairDoneInit(repairInfo?.ID!!)

    }

    override fun initListener() {


        rg_view.setOnCheckedChangeListener { group, checkedId ->
            when (checkedId) {
                R.id.rb_custom_company -> {
                    rb_custom_company.isChecked = true
                }
                R.id.rb_custom_personal -> {
                    rb_custom_personal.isChecked = true
                }

            }
        }
        rb_custom_company.setOnClickListener(DuplicateClickProxy(this))
        rb_custom_personal.setOnClickListener(DuplicateClickProxy(this))
        btn_save.setOnClickListener(DuplicateClickProxy(this))
        btn_update.setOnClickListener(DuplicateClickProxy(this))
    }

    var custType = ""
    var callPhotos = ""
    override fun onClick(v: View?) {
        when (v?.id) {
            R.id.btn_save -> {
                save(1)
            }
            R.id.btn_update -> {

                save(0)
            }
            R.id.rb_custom_company -> {
                custType = "1"
                rb_custom_company.isChecked = true

            }
            R.id.rb_custom_personal -> {
                custType = "2"
                rb_custom_personal.isChecked = true
            }
        }
    }

    private fun save(type: Int) {
        if (list.size > 0) {
            mPresenter.upFile(list, type)
        } else {
            fileUploadSuccess(mutableListOf(), type)
        }

    }

    override fun descSuccess(data: ReportData) {
        this.data = data
        ShowRevenue01.visibility = if (data.RepairInfo.ShowRevenue01) View.VISIBLE else View.GONE
        ShowRevenue02.visibility = if (data.RepairInfo.ShowRevenue02) View.VISIBLE else View.GONE
        ShowRevenue03.visibility = if (data.RepairInfo.ShowRevenue03) View.VISIBLE else View.GONE
        ShowRevenue04.visibility = if (data.RepairInfo.ShowRevenue04) View.VISIBLE else View.GONE
        ShowRevenue05.visibility = if (data.RepairInfo.ShowRevenue05) View.VISIBLE else View.GONE

        Revenue01Name.text = "${data.RepairInfo.Revenue01Name}"
        Revenue02Name.text = "${data.RepairInfo.Revenue02Name}"
        Revenue03Name.text = "${data.RepairInfo.Revenue03Name}"
        Revenue04Name.text = "${data.RepairInfo.Revenue04Name}"
        Revenue05Name.text = "${data.RepairInfo.Revenue05Name}"
        RecyclerWLValue.isChecked = data.RepairInfo.Remark2 == "1"
        LSCKValue.setText(data.RepairInfo.Remark3)
        ShowLSCK.visibility = if (data.ShowLLCK) View.VISIBLE else View.GONE
        ShowRecyclerWl.visibility = if (data.ShowWLHS) View.VISIBLE else View.GONE

        Revenue01.setText(
            if (data.RepairInfo.Revenue01?.isEmpty() == true) "" else data.RepairInfo.Revenue01
        )
        Revenue02.setText(
            if (data.RepairInfo.Revenue02?.isEmpty() == true) "" else data.RepairInfo.Revenue02
        )
        Revenue03.setText(
            if (data.RepairInfo.Revenue03?.isEmpty() == true) "" else data.RepairInfo.Revenue03
        )
        Revenue04.setText(
            if (data.RepairInfo.Revenue04?.isEmpty() == true) "" else data.RepairInfo.Revenue04
        )
        Revenue05.setText(
            if (data.RepairInfo.Revenue05?.isEmpty() == true) "" else data.RepairInfo.Revenue05
        )

        Revenue01Value = Revenue01.text.toString()
        Revenue02Value = Revenue02.text.toString()
        Revenue03Value = Revenue03.text.toString()
        Revenue04Value = Revenue04.text.toString()
        Revenue05Value = Revenue05.text.toString()
        revenueTotal()
        Revenue01.addTextChangedListener(object : EdiTextChangeListener() {
            override fun showText(text: String) {
                Revenue01Value = text
                revenueTotal()
            }
        })
        Revenue02.addTextChangedListener(object : EdiTextChangeListener() {
            override fun showText(text: String) {
                Revenue02Value = text
                revenueTotal()
            }
        })
        Revenue03.addTextChangedListener(object : EdiTextChangeListener() {
            override fun showText(text: String) {
                Revenue03Value = text
                revenueTotal()
            }
        })
        Revenue04.addTextChangedListener(object : EdiTextChangeListener() {
            override fun showText(text: String) {
                Revenue04Value = text
                revenueTotal()
            }
        })
        Revenue05.addTextChangedListener(object : EdiTextChangeListener() {
            override fun showText(text: String) {
                Revenue05Value = text
                revenueTotal()
            }
        })


        ShowExpense01.visibility = if (data.RepairInfo.ShowExpense01) View.VISIBLE else View.GONE
        ShowExpense02.visibility = if (data.RepairInfo.ShowExpense02) View.VISIBLE else View.GONE
        ShowExpense03.visibility = if (data.RepairInfo.ShowExpense03) View.VISIBLE else View.GONE
        ShowExpense04.visibility = if (data.RepairInfo.ShowExpense04) View.VISIBLE else View.GONE
        ShowExpense05.visibility = if (data.RepairInfo.ShowExpense05) View.VISIBLE else View.GONE

        Expense01Name.text = "${data.RepairInfo.Expense01Name}"
        Expense02Name.text = "${data.RepairInfo.Expense02Name}"
        Expense03Name.text = "${data.RepairInfo.Expense03Name}"
        Expense04Name.text = "${data.RepairInfo.Expense04Name}"
        Expense05Name.text = "${data.RepairInfo.Expense05Name}"

        et_RepairDescr.setText(data.RepairInfo.RepairDescr)
        Expense01.setText(
            if (data.RepairInfo.Expense01?.isEmpty() == true) "" else data.RepairInfo.Expense01
        )
        Expense02.setText(
            if (data.RepairInfo.Expense02?.isEmpty() == true) "" else data.RepairInfo.Expense02
        )
        Expense03.setText(
            if (data.RepairInfo.Expense03?.isEmpty() == true) "" else data.RepairInfo.Expense03
        )
        Expense04.setText(
            if (data.RepairInfo.Expense04?.isEmpty() == true) "" else data.RepairInfo.Expense04
        )
        Expense05.setText(
            if (data.RepairInfo.Expense05?.isEmpty() == true) "" else data.RepairInfo.Expense05
        )

        Expense01Value = Expense01.text.toString()
        Expense02Value = Expense02.text.toString()
        Expense03Value = Expense03.text.toString()
        Expense04Value = Expense04.text.toString()
        Expense05Value = Expense05.text.toString()

        expenseTotal()
        Expense01.addTextChangedListener(object : EdiTextChangeListener() {
            override fun showText(text: String) {

                Expense01Value = text
                expenseTotal()
            }
        })
        Expense02.addTextChangedListener(object : EdiTextChangeListener() {
            override fun showText(text: String) {

                Expense02Value = text
                expenseTotal()
            }
        })
        Expense03.addTextChangedListener(object : EdiTextChangeListener() {
            override fun showText(text: String) {

                Expense03Value = text
                expenseTotal()
            }
        })
        Expense04.addTextChangedListener(object : EdiTextChangeListener() {
            override fun showText(text: String) {

                Expense04Value = text
                expenseTotal()
            }
        })
        Expense05.addTextChangedListener(object : EdiTextChangeListener() {
            override fun showText(text: String) {

                Expense05Value = text
                expenseTotal()
            }
        })
        rg_view.check(
            if (data.RepairInfo.CustType == 2) R.id.rb_custom_company else if (data.RepairInfo.CustType == 1) R.id.rb_custom_personal
            else -1
        )
        if (!data.RepairInfo.CallPhotos.isNullOrEmpty()) {
            callPhotos = data.RepairInfo.CallPhotos;
            list.addAll(callPhotos.split(",").toList())

        }
        tv_picnum.text = "( ${list.size}/${data.CallPhotosMaxQty} )"

        mAdapter = OrderReportPhotoItemAdapter(
            mContext,
            list,
            data.CallPhotosMaxQty,
            R.layout.item_pic_layout
        )
        gv_list.apply {
            itemAnimator = null
            layoutManager = GridLayoutManager(context, 3)

        }
        gv_list.addItemDecoration(GridSpacingItemDecoration(DisplayUtil.dip2px(this, 5f), false))
        gv_list.adapter = mAdapter

        mAdapter?.setOnItemClickListener { i ->
            if (list.size < data.CallPhotosMaxQty && i == list.size) {
                ImagePicker.withMulti(WeChatPresenter())//设置presenter
                    .setMaxCount(data.CallPhotosMaxQty - list.size)//设置选择数量
                    .showCamera(true)//设置显示拍照
                    .setPreview(true)
                    .setColumnCount(4)//设置列数
                    .mimeTypes(MimeType.ofImage())//设置需要加载的文件类型
                    .filterMimeTypes(MimeType.GIF)//设置需要过滤掉的文件类型
                    //  .assignGapState(false)//强制留白模式
                    //  .setFirstImageItem(null)//设置上一次选中的图片
                    //  .setFirstImageItemSize(1, 1)//设置上一次选中的图片地址
                    .setVideoSinglePick(true)//设置视频单选
                    .setMaxVideoDuration(1200000L)//设置可选区的最大视频时长
                    .setMinVideoDuration(60000L)//设置视频可选取的最小时长
                    .pick(mContext as Activity?, object : OnImagePickCompleteListener {
                        override fun onImagePickComplete(items: ArrayList<ImageItem>) {
                            //图片剪裁回调，主线程
                            //注意：剪裁回调里的ImageItem中getCropUrl()才是剪裁过后的图片地址
                            if (items.size > 0) {
                                for (item in items) {
                                    list.add("file://" + item.path)
                                }
                                mAdapter?.notifyDataSetChanged()
                            }
                            tv_picnum.text = "( ${list.size}/${data?.CallPhotosMaxQty} )"
                        }
                    })
            } else {

            }
        }
    }

    private fun revenueTotal() {
        var total = 0.toBigDecimal()
        if (!Revenue01Value.isEmpty())
            total += Revenue01Value.toBigDecimal()

        if (!Revenue02Value.isEmpty())
            total += Revenue02Value.toBigDecimal()
        if (!Revenue03Value.isEmpty())
            total += Revenue03Value.toBigDecimal()

        if (!Revenue04Value.isEmpty())
            total += Revenue04Value.toBigDecimal()

        if (!Revenue05Value.isEmpty())
            total += Revenue05Value.toBigDecimal()

        RevenueTotal.text = "$total"
    }

    private fun expenseTotal() {
        var total = 0.toBigDecimal()
        if (!Expense01Value.isEmpty())
            total += Expense01Value.toBigDecimal()

        if (!Expense02Value.isEmpty())
            total += Expense02Value.toBigDecimal()
        if (!Expense03Value.isEmpty())
            total += Expense03Value.toBigDecimal()

        if (!Expense04Value.isEmpty())
            total += Expense04Value.toBigDecimal()

        if (!Expense05Value.isEmpty())
            total += Expense05Value.toBigDecimal()


        ExpenseTotal.text = "$total"
    }

    override fun saveSuccess() {
        setResult(RESULT_OK)
        finish()
    }

    override fun fileUploadSuccess(fileList: MutableList<String>, type: Int) {
        callPhotos = ""
        fileList.forEach {
            if (callPhotos.isEmpty()) {
                callPhotos = it
            } else {
                callPhotos += ",$it"
            }
        }
        val RepairDescr = et_RepairDescr.text.toString().trim()

        this.data?.RepairInfo?.Expense01 = this.Expense01Value
        this.data?.RepairInfo?.Expense02 = this.Expense02Value
        this.data?.RepairInfo?.Expense03 = this.Expense03Value
        this.data?.RepairInfo?.Expense04 = this.Expense04Value
        this.data?.RepairInfo?.Expense05 = this.Expense05Value
        this.data?.RepairInfo?.Revenue01 = this.Revenue01Value
        this.data?.RepairInfo?.Revenue02 = this.Revenue02Value
        this.data?.RepairInfo?.Revenue03 = this.Revenue03Value
        this.data?.RepairInfo?.Revenue04 = this.Revenue04Value
        this.data?.RepairInfo?.Revenue05 = this.Revenue05Value
        if (data?.ShowWLHS == true) {
            this.data?.RepairInfo?.Remark2 = if (RecyclerWLValue.isChecked) "1" else "0"
        }
        if (data?.ShowLLCK == true) {
            this.data?.RepairInfo?.Remark3 = LSCKValue.text.toString()
        }
        mPresenter.save(
            activity = this,
            repairId = repairInfo?.ID!!, data = this.data?.RepairInfo!!,
            custType = custType, repairDescr = RepairDescr, callPhotos = callPhotos,
            type = type
        )
    }

    override fun createPresenter(): ReportPresenter {
        return ReportPresenter(this)
    }


}
